import xlrd,xlwt
from collections import defaultdict
from utils.LogUtil import logger_init
from utils.common import json_load,dict_list_add
logger = logger_init('Excel')
class Excel:
    def __init__(self,file):
        self._data = dict()
        book = xlrd.open_workbook(file)
        logger.info("The number of worksheets is {0}".format(book.nsheets))
        logger.info("Worksheet name(s): {0}".format(book.sheet_names()))
        #遍历所有的sheet
        for sheet_name in book.sheet_names():
            n_row_map = defaultdict(list)  # 存放子模块
            sheet = book.sheet_by_name(sheet_name)
            logger.info("{0} {1} {2}".format(sheet.name, sheet.nrows, sheet.ncols))
            #获取列名
            field_row = [i.value for i in sheet.row(0)]
            #从第二行开始遍历所有行
            for rx in range(1,sheet.nrows):
                #把每一行用dict存放
                row = [i.value for i in sheet.row(rx)]
                row_map = dict()
                for j in range(sheet.ncols):
                    if field_row[j] == "输入参数":
                        v = json_load(row[j])
                    else:
                        v= row[j]
                    row_map[field_row[j]] = v
                if row_map['是否运行'] =='yes':
                    sub_module = row_map.get('子模块', None)
                    if sub_module:
                        n_row_map[sub_module].append(row_map)
                    else:
                        dict_list_add(self._data,sheet_name,row_map)
            if not self._data.get(sheet_name,None):
                self._data[sheet_name]=n_row_map

            # logger.info("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
    @property
    def data(self):
        return self._data



# excel = Excel("H:/codes/python/automation/SeleniumAuto/data/testcases.xlsx")
# # print(excel.data)
# for k,v in excel.data.items():
#     print("***"*60)
#     print(k,v)
